local yucheng = fk.CreateSkill{
  name = "rfenghou_3d18j__yucheng",
}

yucheng:addEffect(fk.RoundStart, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(yucheng.name) then return end
    local cards = table.filter(player.room.discard_pile, function(id)
      local card = Fk:getCardById(id)
      return card:isCommonTrick()
    end)
    return cards[1]
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local cards = table.filter(room.discard_pile, function(id)
      local card = Fk:getCardById(id)
      return card:isCommonTrick()
    end)
    if not cards[1] then return end
    if not room:askToSkillInvoke(player, {
      skill_name = yucheng.name,
      prompt = "#rfenghou_3d18j__yucheng-invoke",
    }) then return end
    local cids = room:askToPoxi(player, {
      poxi_type = "AskForCardsChosen",
      data = {
        {"pile_discard", cards},
      },
      extra_data = {
        min = 1,
        max = 1,
        skillName = yucheng.name,
        prompt = "#rfenghou_3d18j__yucheng-invoke",
      },
      cancelable = false
    })
    if cids[1] then
      event:setCostData(self, { cards = cids })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local cards = event:getCostData(self).cards
    player:addToPile(yucheng.name, cards, true, yucheng.name, player)
  end
})
yucheng:addEffect(fk.CardUsing, {
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    if target == player and data.card and data.card.type == Card.TypeTrick then
      return #target:getCardIds("he") >= 2
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local suits = table.reduce(room:getAlivePlayers(false), {}, function(result, element)
      for _, cid in ipairs(element:getPile(yucheng.name)) do
        table.insertIfNeed(result, Fk:getCardById(cid).suit)
      end
      return result
    end)
    if #suits == 0 then return end
    local _, dat = room:askToUseActiveSkill(player, {
      skill_name = "#rfenghou_3d18j__yucheng_active",
      prompt = "#rfenghou_3d18j__yucheng-recast:::" .. table.concat(table.map(suits, function(suit) return Fk:translate(Card.getSuitString({ suit = suit })) end), "、"),
      extra_data = {
        skillName = yucheng.name,
        card_suits = suits,
      },
      cancelable = true,
    })
    if dat then
      event:setCostData(self, { cards = dat.cards })
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local cards = event:getCostData(self).cards
    if not cards or #cards ~= 2 then return end
    player.room:recastCard(cards, player, yucheng.name)
  end
})
yucheng:addEffect(fk.RoundEnd, {
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return player:getPile(yucheng.name)[1]
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local yuchengs = player:getPile(yucheng.name)
    room:moveCards {
      ids = yuchengs,
      from = player,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      skillName = yucheng.name,
      proposer = player,
      moveVisible = true,
    }

    local function yuchengCardCanUse(to)
      for _, cid in ipairs(yuchengs) do
        local card = Fk:getCardById(cid)
        if player:canUseTo(card, to, { bypass_distances = true, bypass_times = true }) then
          return true
        end
      end
      return false
    end

    while #yuchengs > 0 do
      local recasted = {}
      room.logic:getEventsByRule(GameEvent.MoveCards, 1, function(e)
        local e_data = e.data
        for _, move in ipairs(e_data) do
          if move.moveReason == fk.ReasonRecast and move.skillName == yucheng.name and move.from and not table.contains(recasted, move.from) and yuchengCardCanUse(move.from) then
            table.insert(recasted, move.from)
          end
        end
      end, nil, Player.HistoryRound)
      local unrecasted = table.filter(room:getAlivePlayers(false), function(p)
        return not table.contains(recasted, p) and yuchengCardCanUse(p)
      end)
      if #recasted == 0 and #unrecasted == 0 then break end
      local _, dat = room:askToUseActiveSkill(player, {
        skill_name = "#rfenghou_3d18j__yucheng_target",
        prompt = "#rfenghou_3d18j__yucheng-use",
        extra_data = {
          skillName = yucheng.name,
          selecteds = recasted,
          elses = unrecasted,
          expand_pile = yuchengs,
        },
        cancelable = false,
      })
      if dat then
        local tos = table.simpleClone(dat.targets)
        room:sortByAction(tos)
        table.removeOne(yuchengs, dat.cards[1])
        local card = Fk:getCardById(dat.cards[1])
        if card.skill:getSkeleton().name == "collateral_skill" then
          -- SB借刀
          local actualTos = {}
          for _, first_to in ipairs(tos) do
            local use = room:askToUseRealCard(player, {
              pattern = dat.cards,
              expand_pile = dat.cards,
              skill_name = card.name,
              extra_data = {
                must_targets = { first_to.id },
                bypass_times = true,
              },
              skip = true,
              cancelable = false,
            })
            if use then
              table.insertTable(actualTos, use.tos)
            end
          end
          if #actualTos > 1 then
            room:useCard{
              from = player,
              tos = actualTos,
              card = card,
            }
          end
        else
          room:useCard{
            from = player,
            tos = tos,
            card = card,
          }
        end
      else
        break
      end
    end

    room:cleanProcessingArea(nil, yucheng.name)
  end
})

Fk:loadTranslationTable{
  ["rfenghou_3d18j__yucheng"] = "玉秤",
  [":rfenghou_3d18j__yucheng"] = "轮次开始时，你可以将弃牌堆中一张普通锦囊牌置于武将牌上；本轮一名角色使用锦囊牌时，可以重铸两张与之花色相同的牌。轮次结束时，你移去所有“玉秤”牌并对所有本轮如此或未如此做的角色使用之。",

  ["#rfenghou_3d18j__yucheng-invoke"] = "玉秤：你可以将弃牌堆中一张普通锦囊牌置于武将牌上；<br>本轮一名角色使用锦囊牌时，可以重铸两张与之花色相同的牌",
  ["#rfenghou_3d18j__yucheng-recast"] = "玉秤：你可以重铸两张%arg牌",
  ["#rfenghou_3d18j__yucheng-use"] = "玉秤：你须对本轮重铸过牌或未重铸牌的所有角色使用“玉秤”牌",
}

return yucheng
